package ensib.sti.ssu;

import ensib.sti.ssu.DAO.BlocNoteDAO;
import ensib.sti.ssu.activities.AjoutNoteActivity;
import ensib.sti.ssu.activities.Preference;
import ensib.sti.ssu.activities.PreferencesSauvegarde;
import ensib.sti.ssu.activities.RappelActivity;
import ensib.sti.ssu.activities.RestaurerDonnerActivity;
import ensib.sti.ssu.activities.SauvegardeDonnerActivity;
 
import ensib.sti.ssu.beans.BlocNote;
import ensib.sti.ssu.classes.Parler;
import ensib.sti.ssu.classes.Utilitaire;
import android.net.Uri;
import android.net.Uri.Builder;
import android.os.Bundle;
 
import android.preference.PreferenceManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.SearchManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
 
import java.util.ArrayList;
 
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
 
 
 
import android.app.AlertDialog;
 
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
 
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Color;
 
 
 
import android.widget.AdapterView;
 
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
 
public class BlocNoteActivity extends Activity {
	private ListView blocnotelist;
	private BlocNoteDAO dao;
	private int preference;
	 List<BlocNote> liste;
	 BlocNote note=null;
	private int CODE_PREFERENCE_ACTIVITY=0x1128;
	private int CODE_PREFERENCE_SAUVEGARDE_ACTIVITY=0x1006;
	
	public final static int AJOUT_NOTE_ACTIVITY_CODE=0x1000;
	public final static int SAUVEGARDE_ACTIVITY_CODE=0x1002;
	public final static int RESTAURATION_DONNEES_ACTIVITY_CODE=0x1002;
	public final static int ACTIVITE_AJOUT_NOTE_CODE=0x1020;
	private final static String storageKey="BLOC_NOTE_PREFERENCE";
	
	public final static int SORT_BY_PRIORITY=0x01;
	public final static int SORT_BY_DEADLINE=0x02;
	public final static int SORT_BY_TYPE=0x03;
	public final static int SORT_BY_TACHE_NAME=0x04;
	public final int SORT_BY_DESCRIPTION=0x5;
	
	Button restaurer,sauvegarder;
	private EditText searchinput;
	private Parler jeparle;
 //Thread rappelTache;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bloc_note);
		blocnotelist=(ListView) findViewById(R.id.blocnotelist);
		 Button nouveau=(Button) findViewById(R.id.ajouternote);
				 restaurer=(Button) findViewById(R.id.restaurernote);
				 sauvegarder=(Button) findViewById(R.id.sauvegardernote);
				 searchinput= ((EditText) findViewById(R.id.inputSearchedittext));
				 jeparle=new Parler(getApplicationContext());
				 
		 performpreference();
	  
		    //((EditText) findViewById(R.id.inputSearchedittext))searchinput.setHint(preference+"");
		 nouveau.setOnClickListener(new android.view.View.OnClickListener() {
			
		

			@Override
			public void onClick(View v) {
				 
				Intent t=new Intent(BlocNoteActivity.this, AjoutNoteActivity.class);
				startActivityForResult (t,ACTIVITE_AJOUT_NOTE_CODE);
			}
		});
		restaurer.setOnClickListener(new android.view.View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					 
					Intent t=new Intent(BlocNoteActivity.this, RestaurerDonnerActivity.class);
					startActivityForResult(t,RESTAURATION_DONNEES_ACTIVITY_CODE);
				}
			});
		 sauvegarder.setOnClickListener(new android.view.View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					 
					Intent t=new Intent(BlocNoteActivity.this, SauvegardeDonnerActivity.class);
					dao.open();
					ArrayList<BlocNote> l = (ArrayList<BlocNote>) dao.findAll();
					dao.close();
					Bundle b=new Bundle();
					b.putParcelableArrayList("notes", l);
					t.putExtras(b);
					startActivityForResult(t,SAUVEGARDE_ACTIVITY_CODE);
				}
			});
		  dao=new BlocNoteDAO(getApplicationContext());
		   
        traitement(null);
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(getBaseContext());
            	if(prefs.getBoolean("activer_rappel_tache_key", false))
    	  startActivity(new Intent(this,RappelActivity.class));
    	
    	  
	}
	
	private void traitement(ArrayList<BlocNote> liste1) {
		// TODO Auto-generated method stub
		 HashMap<String, String>  map;
		 ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
		 
	     
	       /*
	        * 
	        */
	       
	         
	       performpreference();
	       //  dao.insertBlocNote(note);
	       if(liste1==null){
	    	   dao.open();
	       liste=dao.findAll();
	       dao.close();
	       }else
	    	   liste=liste1;
	    
	      if(liste!=null){
	    	  note=liste.get(0);
	    	  Log.i("liste_des_notes",liste.size()+"");
		      sauvegarder.setEnabled(true);
		     // searchinput.setHint(preference+"");
	          liste=Utilitaire.trier(liste,preference);
	          
	          String haute=String.valueOf(R.drawable.priorite_haute),
	        		  basse=String.valueOf(R.drawable.priorite_basse),
	        		  moyenne = String.valueOf(R.drawable.priorite_moyenne);
	        for (BlocNote blocNote : liste) {
	     	   map = new HashMap<String, String>();
	     	   map.put("nomtache",  blocNote.getNomTache());
	     	    
	     	   map.put("date",  blocNote.getDeadLineDateToString());
	     	   map.put("prioriteimg","");
	     	   switch (blocNote.getPriorite()) {
			case BlocNote.PRIORITE_HAUTE:
				  map.put("img", haute);
				break;
            case BlocNote.PRIORITE_BASSE:
            	  map.put("img", basse);
				break;
              case BlocNote.PRIORITE_MOYENNE:
            	  map.put("img", moyenne);
	break;
			}
	     	 
	     	   listItem.add(map);
	 	}} else  sauvegarder.setEnabled(false);
	     
	 
	         
	 
	         final SimpleAdapter adapter = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.itemlayout,
	               new String[] {"img", "nomtache", "date","prioriteimg"}, new int[] {R.id.item_img, R.id.item_nomtache, R.id.item_date,R.id.item_prioriteimg});
	// blocnotelist.removeAllViews();
	        
	         blocnotelist.setAdapter(adapter);
	        
	        searchinput.addTextChangedListener(new TextWatcher() {
			     
				    @Override
				    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
				        // When user changed the Text
				         adapter.getFilter().filter(cs);  
				    }
				     
				    @Override
				    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				            int arg3) {
				        // TODO Auto-generated method stub
				         
				    }
				     
				    @Override
				    public void afterTextChanged(Editable arg0) {
				        // TODO Auto-generated method stub                         
				    }
				});
	          blocnotelist.setOnItemClickListener(new OnItemClickListener() {
				@Override
	        	@SuppressWarnings("unchecked")
	         	public void onItemClick(AdapterView<?> a, View v, int position, long id) {
					 HashMap<String, String> map = (HashMap<String, String>) blocnotelist.getItemAtPosition(position);
	        		 final AlertDialog.Builder adb = new AlertDialog.Builder(BlocNoteActivity.this);
	        		 final String nomtache=map.get("nomtache");
	        		  dao.open();
	        		  
	        		
	        		 if(nomtache==null)
	        			 note=dao.findAll().get(0);
	        		 else
	        			 note=dao.getBlocNoteBlocNoteByNomTache(nomtache);
	        		 dao.close();
	        		 adb.show();
	        		 
	        		 LayoutInflater factory = LayoutInflater.from(BlocNoteActivity.this);
	        	        final View alertDialogView = factory.inflate(R.layout.afficher_note, null);
	        	      TextView   description=(TextView) alertDialogView.findViewById(R.id.afficher_note_description),
	        	    		     //
	        	    		  
	        	    		 // nomtacheview=(TextView) alertDialogView.findViewById(R.id.afficher_note_nomtache),
	        	    		     dateview=(TextView) alertDialogView.findViewById(R.id.afficher_date);
	        	       //**
	        	     //( (Button) alertDialogView.findViewById(R.id.)).setVisibility(Button.INVISIBLE);
	        	    		     description.setText(note.getDescription());
	        	    		    // nomtacheview.setVisibility(View.INVISIBLE);
	        	    		     if(note.getPriorite()==BlocNote.PRIORITE_HAUTE)
	        	    		    	 description.setBackgroundColor(Color.RED);
	        	    		     else   if(note.getPriorite()==BlocNote.PRIORITE_MOYENNE)
	        	    		    	 description.setBackgroundColor(Color.YELLOW);
	        	    		     else
	        	    		    	 description.setBackgroundColor(Color.GREEN);
	        	    		    // nomtacheview.setText(note.getNomTache());
	        	    		    // Date d=new Date(note.getDeadLineDate());
	        	    		     dateview.setText(note.getDeadLineDateToString());
	        		 adb.setTitle(note.getNomTache());
	        		  adb.setView(alertDialogView);
	        		  //adb.setIcon(R.drawable.icon);
	        		  adb.setNeutralButton(BlocNoteActivity.this.getResources().getString(R.string.annuler),  null);
	        		  adb.setNegativeButton(BlocNoteActivity.this.getResources().getString(R.string.supprimer),new android.content.DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							AlertDialog.Builder adb = new AlertDialog.Builder(BlocNoteActivity.this);
			        		adb.setTitle(BlocNoteActivity.this.getResources().getString(R.string.label_lors_suppression));
			        		adb.setMessage(BlocNoteActivity.this.getResources().getString(R.string.message_lors_suppression));
			        		adb.setNegativeButton(BlocNoteActivity.this.getResources().getString(R.string.non), null);
			        		  adb.setPositiveButton(BlocNoteActivity.this.getResources().getString(R.string.oui), new android.content.DialogInterface.OnClickListener(){

								@Override
								public void onClick(DialogInterface arg0, int arg1) {
									// TODO Auto-generated method stub
									dao.open();
									 dao.removeBlocNote(note);
									 traitement(null);
									 jeparle.setMessage( note.getNomTache()+", "+BlocNoteActivity.this.getResources().getString(R.string.message_note_supprimee)).parle();
								        
									dao.close();
									 
								}

								 
			        			  
			        		  });
			        		  adb.show();
						}
					});
							
	        			  
	        		  adb.setPositiveButton(BlocNoteActivity.this.getResources().getString(R.string.modifier),new android.content.DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							AlertDialog.Builder adb = new AlertDialog.Builder(BlocNoteActivity.this);
			        		 
			        		 
			        		 LayoutInflater factory = LayoutInflater.from(BlocNoteActivity.this);
			        	        final View alertDialogView = factory.inflate(R.layout.ajoutnote, null);
			        	        
			        	     final TextView   description=(TextView) alertDialogView.findViewById(R.id.ajout_description),
			        	    		     nomtacheview=(TextView) alertDialogView.findViewById(R.id.ajout_nomtache),
			        	    		     dateview=(TextView) alertDialogView.findViewById(R.id.ajout_date);
			        	      final Spinner  priorite= (Spinner) alertDialogView.findViewById(R.id.ajout_priorite);
			        	      
			        	      ( (Button) alertDialogView.findViewById(R.id.ajout_annuler_bouton)).setVisibility(Button.INVISIBLE);
			        	      ( (Button) alertDialogView.findViewById(R.id.ajout_valider_bouton)).setVisibility(Button.INVISIBLE);
				        	  
			        	    		 //String[] priorite_data=BlocNoteActivity.this.getResources().getStringArray(R.string.priorite_arrays);
							final Spinner typetache=(Spinner) alertDialogView.findViewById(R.id.ajout_typetache);
							ArrayAdapter  adapter = ArrayAdapter.createFromResource(BlocNoteActivity.this, R.array.priorite_arrays, R.layout.prioritespinner),
							
							adapter2 = ArrayAdapter.createFromResource(BlocNoteActivity.this, R.array.type_tache_arrays, R.layout.prioritespinner);
							
							adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
							adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							typetache.setAdapter(adapter2);
							priorite.setAdapter(adapter);
			        	      description.setText(note.getDescription());
			        	    		     nomtacheview.setText(note.getNomTache());
			        	    		    // Date d=new Date(note.getDeadLineDate());
			        	    		     dateview.setText(note.getDeadLineDateToString());
			        	    		     
			        	    		     Utilitaire.showImage(note.getPhotoUrl(),R.id.affichage_image , BlocNoteActivity.this);
			        	    		     
			        		 adb.setTitle(note.getNomTache());
			        		  adb.setView(alertDialogView);
			        		  adb.setNegativeButton(BlocNoteActivity.this.getResources().getString(R.string.annuler), null);
			        		  adb.setPositiveButton(BlocNoteActivity.this.getResources().getString(R.string.valider), new android.content.DialogInterface.OnClickListener(){

								@Override
								public void onClick(DialogInterface arg0, int arg1) {
									// TODO Auto-generated method stub
									dao.open();
									note.setDescription(description.getText().toString());
									note.setDeadLineDate((dateview.getText().toString()));
									note.setNomTache(nomtacheview.getText().toString());
									note.setPriorite( (String) ((priorite.getSelectedItem())));
									note.setTypeTache(((String)typetache.getSelectedItem()));
									dao.updateBlocNote(note);
									
									 traitement(null);
									 jeparle.setMessage( note.getNomTache()+", "+BlocNoteActivity.this.getResources().getString(R.string.message_note_modifiee)).parle();
							        	
									dao.close();
									 
								}

								 
			        			  
			        		  });
			        		  adb.show();
			        		  //adb.setIcon(R.drawable.icon);
			        		  
						}
					}); 
	        		 adb.show();
	        		 jeparle.setMessage( note.getNomTache()+", descripton:"+note.getDescription()+", date:"+note.getDeadLineDateToString()).parle();
	        	}
	         });
	 
	
	}
	

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		
		SharedPreferences setting=getPreferences(MODE_PRIVATE);
		 Editor edit = setting.edit();
		 edit.putInt(storageKey, preference);
		 edit.commit();
		 jeparle.arreter();
		 super.onStop();
	}
	 
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK ){
	    	if(requestCode==RESTAURATION_DONNEES_ACTIVITY_CODE){
	        if (data.hasExtra("notesrestaurees")) {
	            ArrayList<BlocNote> l=data.getExtras().getParcelableArrayList("notesrestaurees");
	            if(l!=null&&l.size()>0){
	            	dao.open();
	            	dao.insertOrUpdate(l);
	            	dao.close();
				traitement(null);
	             Log.i("data_restaure", ""+l.size());
	              
	            }
	        }
	    }else if(requestCode==CODE_PREFERENCE_ACTIVITY){
	    	performpreference();
	    	 traitement(null);
	    
		}else if(requestCode==ACTIVITE_AJOUT_NOTE_CODE){
	    	 
	    	traitement(null);
	    }
	    	
		}
	}
 
	public void performpreference(){
		SharedPreferences setting = PreferenceManager.getDefaultSharedPreferences(this);
		 
		 
			preference=Integer.parseInt(setting.getString(storageKey,( ""+SORT_BY_DEADLINE)).trim());
			 
	}
	

	@SuppressLint("NewApi")
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.bloc_note, menu);
		// Associate searchable configuration with the SearchView
	    SearchManager searchManager =
	           (SearchManager) getSystemService(Context.SEARCH_SERVICE);
	    SearchView searchView =
	            (SearchView) menu.findItem(R.id.search).getActionView();
	    searchView.setSearchableInfo(
	            searchManager.getSearchableInfo(getComponentName()));
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

  final int id=item.getItemId();
  switch (id) {
case  R.id.preferencesetting:
	startActivityForResult(new Intent(this, Preference.class), CODE_PREFERENCE_ACTIVITY);
	break;
case R.id.parametresauvegarde:
	startActivityForResult(new Intent(this, PreferencesSauvegarde.class), CODE_PREFERENCE_SAUVEGARDE_ACTIVITY);
	break;
case R.id.abousUs:
	if(jeparle.iSpalyBackOn()){
	jeparle.setMessage(getResources().getString(R.string.aboutusmessage)).parle();
	}else{
		AlertDialog.Builder adb = new AlertDialog.Builder(BlocNoteActivity.this);
		adb.setTitle(BlocNoteActivity.this.getResources().getString(R.string.aboutus));
		adb.setMessage(BlocNoteActivity.this.getResources().getString(R.string.aboutusmessage));
		adb.setNeutralButton(BlocNoteActivity.this.getResources().getString(R.string.annuler), null);
		adb.show();
	}
default:
	break;
}
  return true;
  
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		traitement(null);
	}

}

//for search input http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/